﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using MachineQA.Model;

namespace MachineQA.DataAccess
{
    public class LocationRepository : ILocationRepository
    {
        readonly List<Location> _locations;
        readonly QADatabaseEntities _entities;

        public LocationRepository(ref QADatabaseEntities entityModel)
        {
            _locations = entityModel.Locations.ToList();
            _entities = entityModel;
        }

        #region Public Interface
        
        public event EventHandler<LocationAddedOrRemovedEventArgs> LocationAddedOrRemoved;
        
        public void AddLocation(Location location)
        {
            if (!_locations.Contains(location))
            {
                _locations.Add(location);
                _entities.AddToLocations(location);
                _entities.SaveChanges(); // persist to db.
                if(this.LocationAddedOrRemoved != null)
                    this.LocationAddedOrRemoved(this, new LocationAddedOrRemovedEventArgs(location, true));
            }
        }

        public void RemoveLocation(Location location)
        {
            if (_locations.Contains(location))
            {
                _locations.Remove(location);
                _entities.Locations.DeleteObject(location);
                _entities.SaveChanges(); // persist to db.
                if (this.LocationAddedOrRemoved != null)
                    this.LocationAddedOrRemoved(this, new LocationAddedOrRemovedEventArgs(location, false));
            }
        }

        /// <summary>
        /// Returns a shallow copied list of all the locations.
        /// </summary>
        /// <returns>A list containing the locations.</returns>
        public List<Location> GetLocations()
        {
            return _locations;
        }

        public bool ContainsLocation(Location location)
        {
            return _locations.Contains(location);
        }

        #endregion // Public Interface
    }
}
